package com.faithbj.controller.firstverify;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.faithbj.common.configuration.Pager;
import com.faithbj.common.model.CheckTotal;
import com.faithbj.common.model.Dictionary;
import com.faithbj.common.model.Enclosure;
import com.faithbj.common.model.Region;
import com.faithbj.common.model.compare.AFMOfficalData;
import com.faithbj.common.model.compare.CivilOfficalData;
import com.faithbj.common.model.compare.HPOfficalData;
import com.faithbj.common.model.compare.IBAOfficalData;
import com.faithbj.common.model.compare.PopulationOfficalData;
import com.faithbj.common.model.compare.SIOfficalData;
import com.faithbj.common.model.compare.TaxOfficalData;
import com.faithbj.common.model.fm.FamilyMember;
import com.faithbj.common.model.fm.property.Bonds;
import com.faithbj.common.model.fm.property.BusinessInsurance;
import com.faithbj.common.model.fm.property.Cars;
import com.faithbj.common.model.fm.property.Deposit;
import com.faithbj.common.model.fm.property.Funds;
import com.faithbj.common.model.fm.property.Futures;
import com.faithbj.common.model.fm.property.House;
import com.faithbj.common.model.fm.property.Stocks;
import com.faithbj.common.model.fm.verify.FamilyMemberIncomeProof;
import com.faithbj.common.model.fm.verify.FamilyMemberIncomeVerify;
import com.faithbj.common.service.RegionService;
import com.faithbj.common.utils.DictionaryUtil;
import com.faithbj.common.web.controller.BaseController;
import com.faithbj.dao.FamilyMemberIncomeVerifyDao;
import com.faithbj.process.ProcessApplicationService;
import com.faithbj.process.State;
import com.faithbj.process.TaskModel;
import com.faithbj.service.CheckTotalService;
import com.faithbj.service.CompareService;
import com.faithbj.service.FamilyMemberIncomeProofService;
import com.faithbj.service.FamilyMemberPropertyService;
import com.faithbj.service.FamilyMemberService;

/**
 * @author jrn E-mail: rinanjin@gmail.com
 * @version 0.1 
 * 创建时间：2012-7-21 上午07:17:37
 * 类说明
 */
@Controller
@RequestMapping(value = "/firstverify")
public class FirstVerifyController extends BaseController
{
	private static final long serialVersionUID = 1L;
	
	private static final String INDEX = "/firstVerify/index";
	
	private static final String FAMILYBASIC = "/firstVerify/main";
	
	private static final String FAMILYMEMBERBASIC = "/firstVerify/familyMemberBasic";
	
	private static final String FAMILYMEMBERINCOME = "/firstVerify/familyMemberIncome";
	
	private static final String FAMILYMEMBERPROPERTY = "/firstVerify/familyMemberProperty";
	
	private static final String STOPVERIFY = "/firstVerify/stopVerify";
	
	private static final String VERIFYINFO = "/firstVerify/verifyInfo";
	
	private static final String VERIFYTABLE = "/firstVerify/verifyTable";
	
	@Resource
	private CheckTotalService checkTotalService;
	
	@Resource
	private DictionaryUtil dictionaryUtil;
	
	@Resource
	private RegionService regionService;
	
	@Resource
	private FamilyMemberService familyMemberService;
	
	@Resource
	private FamilyMemberPropertyService familyMemberPropertyService;
	
	@Resource
	private ProcessApplicationService processApplicationService;
	
	@Resource
	private CompareService compareService;
	
	@Resource
	private FamilyMemberIncomeVerifyDao familyMemberIncomeVerifyDao;
	
	@Resource
	private FamilyMemberIncomeProofService familyMemberIncomeProofService;
	
	@RequestMapping(value = "/index", produces="application/json;charset=UTF-8")
	public String index(Pager pager, ModelMap map)
	{
		if(pager == null)
		{
			pager = new Pager();
		}
		List<TaskModel> tasks = processApplicationService.listAllAvailableTasksWithContentByState(State.FIRST_CHECK_MODIFICATION, pager.getFirstResult(), pager.getPageSize());
		List<CheckTotal> checkTotals = new ArrayList<CheckTotal>();
		for(TaskModel task : tasks)
		{
			CheckTotal checkTotal = task.getCheckTotal();
			checkTotal.getEntrustInfo();
			checkTotals.add(checkTotal);
		}
		pager.setResult(tasks);
		pager.setTotalCount(20);
		map.put("checkTotals", checkTotals);
		map.put("pager", pager);
		return INDEX;
	}
	
	@RequestMapping(value = "/familybasic/{id}/{taskId}/{result}")
	public String familyBasic(@PathVariable("id") String id, @PathVariable("taskId") Long taskId,@PathVariable("result") Boolean result, ModelMap map)
	{
		CheckTotal checkTotal = checkTotalService.getCheckTotalById(id);
		Set<FamilyMember> members = checkTotal.getFamilyMembers();
		for (FamilyMember fm : members)
		{
			if (fm.getMainApplicant())
			{
				map.put("fm", fm);
			}
		}
		List<Dictionary> types = dictionaryUtil.getListByTypeName("业务类型");
		List<Dictionary> idTypes = dictionaryUtil.getListByTypeName("证件类型");
		List<Dictionary> nations = dictionaryUtil.getListByTypeName("民族");
		List<Dictionary> politicalStatusList = dictionaryUtil.getListByTypeName("政治面貌");
		List<Dictionary> education = dictionaryUtil.getListByTypeName("文化程度");
		List<Dictionary> laborlost = dictionaryUtil.getListByTypeName("丧劳情况");
		List<Dictionary> maritalStatusList = dictionaryUtil.getListByTypeName("婚姻状况");
		List<Dictionary> householdTypeList = dictionaryUtil.getListByTypeName("户籍类型");
		List<Dictionary> disabilityDegreeList = dictionaryUtil.getListByTypeName("残疾等级");
		List<Dictionary> relaitionList = dictionaryUtil.getListByTypeName("与申请人代表关系");

		List<Region> citys = regionService.getRegionListByType(Region.COUNTRY);
		List<Region> streets = regionService.getRegionListByType(Region.STREET);

		map.put("taskId", taskId);
		map.put("id", id);
		map.put("members", members);
		map.put("educations", education);
		map.put("laborlost", laborlost);
		map.put("maritalStatusList", maritalStatusList);
		map.put("politicalStatusList", politicalStatusList);
		map.put("nations", nations);
		map.put("citys", citys);
		map.put("streets", streets);
		map.put("types", types);
		map.put("idTypes", idTypes);
		map.put("householdTypes", householdTypeList);
		map.put("disabilityDegreeList", disabilityDegreeList);
		map.put("relaitionList", relaitionList);

		map.put("checkTotal", checkTotal);
		return FAMILYBASIC;
	}
	
	@RequestMapping(value = "/familymemberbasic/{id}/{memberId}/{familyMemberId}/{taskId}")
	public String familyMemberBasic(@PathVariable String id, @PathVariable String memberId, @PathVariable String familyMemberId, @PathVariable("taskId") Long taskId, ModelMap map)
	{
		List<FamilyMember> familyMembers = familyMemberService.getFamilyMembersByCheckTotal(id);
		for(FamilyMember member : familyMembers)
		{
			if(member.getId().equals(familyMemberId))
			{
				map.put("fm", member);
			}
		}
		map.put("members", familyMembers);

		List<Dictionary> types = dictionaryUtil.getListByTypeName("业务类型");
		List<Dictionary> idTypes = dictionaryUtil.getListByTypeName("证件类型");
		List<Dictionary> nations = dictionaryUtil.getListByTypeName("民族");
		List<Dictionary> politicalStatusList = dictionaryUtil.getListByTypeName("政治面貌");
		List<Dictionary> education = dictionaryUtil.getListByTypeName("文化程度");
		List<Dictionary> laborlost = dictionaryUtil.getListByTypeName("丧劳情况");
		List<Dictionary> maritalStatusList = dictionaryUtil.getListByTypeName("婚姻状况");
		List<Dictionary> householdTypeList = dictionaryUtil.getListByTypeName("户籍类型");
		List<Dictionary> disabilityDegreeList = dictionaryUtil.getListByTypeName("残疾等级");
		List<Dictionary> relaitionList = dictionaryUtil.getListByTypeName("与申请人代表关系");

		List<Region> citys = regionService.getRegionListByType(Region.COUNTRY);
		List<Region> streets = regionService.getRegionListByType(Region.STREET);

		map.put("taskId", taskId);
		map.put("id", id);
		map.put("memberId", memberId);
		map.put("familyMemberId", familyMemberId);
		map.put("educations", education);
		map.put("laborlost", laborlost);
		map.put("maritalStatusList", maritalStatusList);
		map.put("politicalStatusList", politicalStatusList);
		map.put("nations", nations);
		map.put("citys", citys);
		map.put("streets", streets);
		map.put("types", types);
		map.put("idTypes", idTypes);
		map.put("householdTypes", householdTypeList);
		map.put("disabilityDegreeList", disabilityDegreeList);
		map.put("relaitionList", relaitionList);

		return FAMILYMEMBERBASIC;
	}
	
	@RequestMapping(value = "/familymemberincome/{id}/{memberId}/{familyMemberId}/{taskId}")
	public String familyMemberIncome(@PathVariable("id") String id, @PathVariable("memberId") String memberId, @PathVariable String familyMemberId, @PathVariable("taskId") Long taskId, ModelMap map)
	{
		List<FamilyMember> familyMembers = familyMemberService.getFamilyMembersByCheckTotal(id);
		for(FamilyMember member : familyMembers)
		{
			if(member.getId().equals(familyMemberId))
			{
				map.put("fm", member);
			}
		}
		FamilyMemberIncomeVerify familyMemberIncomeVerify = familyMemberIncomeVerifyDao.get(familyMemberId);
		CheckTotal ct = checkTotalService.getCheckTotalById(id);
		map.put("familyMemberIncomeVerify", familyMemberIncomeVerify);
		map.put("members", familyMembers);
		map.put("taskId", taskId);
		map.put("id", id);
		map.put("memberId", memberId);
		map.put("familyMemberId", familyMemberId);
		map.put("checkTotal", ct);
		return FAMILYMEMBERINCOME;
	}
	
	@RequestMapping(value = "/familymemberproperty/{id}/{memberId}/{familyMemberId}/{taskId}")
	public String familyMemberProperty(@PathVariable("id") String id, @PathVariable("memberId") String memberId, @PathVariable String familyMemberId, @PathVariable("taskId") Long taskId, ModelMap map)
	{
		FamilyMember currentMember = null;
		List<FamilyMember> familyMembers = familyMemberService.getFamilyMembersByCheckTotal(id);
		CheckTotal ct = checkTotalService.getCheckTotalById(id);

		for(FamilyMember member : familyMembers)
		{
			if(member.getId().equals(familyMemberId))
			{
				currentMember = member;
			}
		}
		
		// 根据申请人省份证号和受理编号查询社会保险委办返回数据
		SIOfficalData siofficalData = compareService.getSIOfficalData(currentMember.getIdNumber(), ct.getBatchNum());
		map.put("siofficalData", siofficalData);
		
		// 根据申请人省份证号和受理编号查询公积金委办返回数据
		AFMOfficalData afmofficalData = compareService.getAFMOfficalData(currentMember.getIdNumber(), ct.getBatchNum());
		map.put("afmofficalData", afmofficalData);
		
		// 根据申请人省份证号和受理编号查询税务委办返回数据
		TaxOfficalData taxofficalData = compareService.getTaxOfficalData(currentMember.getIdNumber(), ct.getBatchNum());
		map.put("taxofficalData", taxofficalData);
		
		// 根据申请人省份证号和受理编号查询民政局委办返回数据
		CivilOfficalData civilofficalData = compareService.getCivilOfficalData(currentMember.getIdNumber(), ct.getBatchNum());
		map.put("civilofficalData", civilofficalData);
		
		// 根据申请人省份证号和受理编号查询工商行政管理局委办返回数据
		IBAOfficalData ibaofficalData = compareService.getIBAOfficalData(currentMember.getIdNumber(), ct.getBatchNum());
		map.put("ibaofficalData", ibaofficalData);
		
		// 根据申请人省份证号和受理编号查询公安局委办返回数据
		PopulationOfficalData psofficalData = compareService.getPSOfficalData(currentMember.getIdNumber(), ct.getBatchNum());
		map.put("psofficalData", psofficalData);
		
		// 根据申请人省份证号和受理编号查询房产局委办返回数据
		HPOfficalData hpofficalData = compareService.getHPOfficalData(currentMember.getIdNumber(), ct.getBatchNum());
		map.put("hpofficalData", hpofficalData);
		
		// 存款
		List<Deposit> deposites = familyMemberPropertyService.getDeposits(familyMemberId);
		map.put("deposites", deposites);
		
		// 股票证券
		List<Stocks> stocks = familyMemberPropertyService.getStocks(familyMemberId);
		map.put("stocks", stocks);
		
		// 开放式基金
		List<Funds> openFunds = new ArrayList<Funds>();
		for(Funds fund : familyMemberPropertyService.getFunds(familyMemberId))
		{
			if(fund.isOpen())
			{
				openFunds.add(fund);
			}
		}
		map.put("openFunds", openFunds);
		
		// 封闭式基金
		List<Funds> closeFunds = new ArrayList<Funds>();
		for(Funds fund : familyMemberPropertyService.getFunds(familyMemberId))
		{
			if(!fund.isOpen())
			{
				closeFunds.add(fund);
			}
		}
		map.put("closeFunds", closeFunds);
		
		// 保险
		List<BusinessInsurance> insurances = familyMemberPropertyService.getBusinessInsurances(familyMemberId);
		map.put("insurances", insurances);
		
		// 债券
		List<Bonds> bonds = familyMemberPropertyService.getBonds(familyMemberId);
		map.put("bonds", bonds);
		
		// 期货
		List<Futures> futures = familyMemberPropertyService.getFutures(familyMemberId);
		map.put("futures", futures);
		
		// 机动车辆
		List<Cars> cars = familyMemberPropertyService.getCars(familyMemberId);
		map.put("cars", cars);
		
		// 房产
		List<House> houses = familyMemberPropertyService.getHouses(familyMemberId);
		map.put("houses", houses);
		
		map.put("taskId", taskId);
		map.put("id", id);
		map.put("memberId", memberId);
		map.put("familyMemberId", familyMemberId);
		map.put("checkTotal", ct);
		map.put("members", familyMembers);
		return FAMILYMEMBERPROPERTY;
	}
	
	
	
	@RequestMapping(value = "/stopverify/{id}/{memberId}/{taskId}")
	public String stopVerify(@PathVariable("id") String id, @PathVariable("memberId") String memberId, @PathVariable("taskId") Long taskId, ModelMap map)
	{
		List<FamilyMember> familyMembers = familyMemberService.getFamilyMembersByCheckTotal(id);
		for(FamilyMember member : familyMembers)
		{
			if(member.getId().equals(memberId))
			{
				map.put("fm", member);
			}
		}
		map.put("taskId", taskId);
		map.put("members", familyMembers);
		
		map.put("id", id);
		map.put("memberId", memberId);
		return STOPVERIFY;
	}
	
	@RequestMapping(value = "/verifyinfo/{id}/{memberId}/{taskId}")
	public String verifyInfo(@PathVariable("id") String id, @PathVariable("memberId") String memberId, @PathVariable("taskId") Long taskId, ModelMap map)
	{
		List<FamilyMember> familyMembers = familyMemberService.getFamilyMembersByCheckTotal(id);
		
		List<FamilyMember> members = new ArrayList<FamilyMember>();
		for(FamilyMember member : familyMembers)
		{
			if(member.getId().equals(memberId))
			{
				setMemberProperty(member);
				members.add(member);
				map.put("fm", member);
			}
		}
		for(FamilyMember member : familyMembers)
		{
			if(member != members.get(0))
			{
				setMemberProperty(member);
				members.add(member);
			}
		}
		map.put("taskId", taskId);
		map.put("members", familyMembers);
		
		map.put("id", id);
		map.put("memberId", memberId);
		return VERIFYINFO;
	}
	
	@RequestMapping(value = "/verifytable/{id}/{memberId}/{taskId}")
	public String verifyTable(@PathVariable("id") String id, @PathVariable("memberId") String memberId, @PathVariable("taskId") Long taskId, ModelMap map)
	{
		CheckTotal checkTotal = checkTotalService.getCheckTotalById(id);
		List<FamilyMember> familyMembers = familyMemberService.getFamilyMembersByCheckTotal(id);
		
		for(FamilyMember member : familyMembers)
		{
			if(member.getId().equals(memberId))
			{
				map.put("fm", member);
			}
		}
		map.put("checkTotal", checkTotal);
		map.put("taskId", taskId);
		map.put("members", familyMembers);
		
		map.put("id", id);
		map.put("memberId", memberId);
		
		return VERIFYTABLE;
	}
	
	private void setMemberProperty(FamilyMember member)
	{
		String familyMemberId = member.getId();
		
		// 存款
		List<Deposit> deposites = familyMemberPropertyService.getDeposits(familyMemberId);
		member.setDeposites(deposites);
		
		// 股票证券
		List<Stocks> stocks = familyMemberPropertyService.getStocks(familyMemberId);
		member.setStocks(stocks);
		
		// 开放式基金
		List<Funds> openFunds = new ArrayList<Funds>();
		for(Funds fund : familyMemberPropertyService.getFunds(familyMemberId))
		{
			if(fund.isOpen())
			{
				openFunds.add(fund);
			}
		}
		member.setOpenFunds(openFunds);
		
		// 封闭式基金
		List<Funds> closeFunds = new ArrayList<Funds>();
		for(Funds fund : familyMemberPropertyService.getFunds(familyMemberId))
		{
			if(!fund.isOpen())
			{
				closeFunds.add(fund);
			}
		}
		member.setCloseFunds(closeFunds);
		
		// 保险
		List<BusinessInsurance> insurances = familyMemberPropertyService.getBusinessInsurances(familyMemberId);
		member.setInsurances(insurances);
		
		// 债券
		List<Bonds> bonds = familyMemberPropertyService.getBonds(familyMemberId);
		member.setBonds(bonds);
		
		// 期货
		List<Futures> futures = familyMemberPropertyService.getFutures(familyMemberId);
		member.setFutures(futures);
		
		// 机动车辆
		List<Cars> cars = familyMemberPropertyService.getCars(familyMemberId);
		member.setCars(cars);
		
		// 房产
		List<House> houses = familyMemberPropertyService.getHouses(familyMemberId);
		member.setHouses(houses);
	}
	
	@ResponseBody
	@RequestMapping("/savefamilymemberincome")
	public String saveFamilyMemberIncome(@RequestParam("memberId") String memberId, @RequestParam("incomeDifference") Boolean incomeDifference, @RequestParam("incomeDiffDes") String incomeDiffDes)
	{
		FamilyMember familyMember = familyMemberService.getFamilyMemberById(memberId);
		familyMember.setIncomeDifference(incomeDifference);
		familyMember.setIncomeDiffDes(incomeDiffDes);
		familyMemberService.saveFamilyMember(familyMember);
		return "success";
	}
	
	@ResponseBody
	@RequestMapping("/savefamilymemberproperty")
	public String saveFamilyMemberProperty(@RequestParam("memberId") String memberId, @RequestParam("propertyDifference") Boolean propertyDifference, @RequestParam("propertyDiffDes") String propertyDiffDes)
	{
		FamilyMember familyMember = familyMemberService.getFamilyMemberById(memberId);
		familyMember.setPropertyDifference(propertyDifference);
		familyMember.setPropertyDiffDes(propertyDiffDes);
		familyMemberService.saveFamilyMember(familyMember);
		return "success";
	}
	
	@ResponseBody
	@RequestMapping("/getproofbymemberid/{memberId}/{propertyName}")
	public List<String> getFamilyMemberIncomeProofByMemberId(@PathVariable("memberId") String memberId, @PathVariable("propertyName") String propertyName)
	{
		FamilyMemberIncomeProof familyMemberIncomeProof = familyMemberIncomeProofService.get(memberId);
		List<String> list = familyMemberIncomeProof.getSelectedProffs(propertyName);
		return list;
	}
	
	@ResponseBody
	@RequestMapping("/savefamilymemberincomeproof")
	public String saveFamilyMemberIncomeProof(@RequestParam("memberId") String memberId, @RequestParam("propertyName") String propertyName, HttpServletRequest request)
	{
		String[] values = request.getParameterValues("values");
		FamilyMemberIncomeProof familyMemberIncomeProof = familyMemberIncomeProofService.get(memberId);
		familyMemberIncomeProof.setSelectedProffs(propertyName, values);
		familyMemberIncomeProofService.save(familyMemberIncomeProof);
		return "success";
	}
	
	@ResponseBody
	@RequestMapping("/getenclosurelist")
	public Map<String, Enclosure> getFamilyMemberById(@RequestParam("id") String id, @RequestParam("memberId") String memberId)
	{
		Map<String, Enclosure> enclosureMap = new HashMap<String, Enclosure>();
		List<FamilyMember> familyMembers = familyMemberService.getFamilyMembersByCheckTotal(id);
		for(FamilyMember member : familyMembers)
		{
			if(member.getId().equals(memberId))
			{
				if(member.getEnclosureList() != null)
				{
					for(Enclosure enclosure : member.getEnclosureList())
					{
						enclosureMap.put(enclosure.getFileName(), enclosure);
					}
				}
			}
		}
		return enclosureMap;
	}
}
